package system

import (
	"context"
	"gin-admin/common/dto/response"
	"gin-admin/global"
	"gin-admin/service/dto/request"
	serviceResponse "gin-admin/service/dto/response"
	"gin-admin/utils"
	"time"

	"github.com/mojocn/base64Captcha"
)

var ctx = context.Background()

type CaptchaService struct{}

func NewCaptchaServiceApp() *CaptchaService {
	return &CaptchaService{}
}

func (cs *CaptchaService) GetCaptchaService() (*serviceResponse.CaptchaResponse, *response.ServiceError) {
	var captchaResponse serviceResponse.CaptchaResponse
	captcha := base64Captcha.NewCaptcha(base64Captcha.NewDriverDigit(80, 240, 6, 0.7, 80), base64Captcha.DefaultMemStore)
	id, b64s, answer, err := captcha.Generate()
	if err != nil {
		global.GA_LOGGER.Sugar().Errorw("获取验证码失败", "error", err)
		return nil, response.WrapError(response.FailedCode, response.GetStatusCode(response.FailedCode).Message)
	}
	redisUtils := &utils.RedisUtils{}
	redisUtils.Set(ctx, id, answer, global.GA_CONFIG.Redis.ExpiresAt*time.Second)
	captchaResponse = serviceResponse.CaptchaResponse{
		Id:          id,
		CaptchaData: b64s,
	}
	return &captchaResponse, nil
}

func (cs *CaptchaService) VerifyCaptchaService(requestData *request.VerifyCaptchaRequest) (bool, *response.ServiceError) {
	answer := requestData.Answer
	if answer == global.GA_CONFIG.App.DefaultCaptcha {
		return true, nil
	}
	redisUtils := &utils.RedisUtils{}
	redisAnswer, err := redisUtils.Get(ctx, requestData.Id)
	if err != nil {
		global.GA_LOGGER.Sugar().Errorw("redis获取验证码失败", "error", err)
		return false, response.WrapError(response.FailedCode, response.GetStatusCode(response.FailedCode).Message)
	}
	if redisAnswer != answer {
		return false, nil
	}
	_ = redisUtils.Delete(ctx, requestData.Id)
	return true, nil
}
